package com.leyou.item.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.leyou.common.exception.ExceptionEnum;
import com.leyou.common.exception.LyException;
import com.leyou.common.utils.BeanHelper;
import com.leyou.common.vo.PageResult;
import com.leyou.item.domain.Brand;
import com.leyou.item.dto.BrandDTO;
import com.leyou.item.mapper.BrandMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

@Service
@Transactional
public class BrandService {
    @Autowired
    private BrandMapper brandMapper;

    public PageResult<BrandDTO> brandPageQuery(String key, Integer page, Integer rows, String sortBy, Boolean desc) {
        PageHelper.startPage(page, rows);
        Example example = new Example(Brand.class);
        if (StringUtils.isNotBlank(key)) {
            Example.Criteria criteria = example.createCriteria();
            criteria.orLike("name", "%" + key + "%");
            criteria.orEqualTo("letter", key.toUpperCase());
        }
        example.setOrderByClause(sortBy+" "+(desc ? "DESC" : "ASC"));
        List<Brand> brands = brandMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(brands)){
            throw new LyException(ExceptionEnum.BRAND_NOT_FOUND);
        }
        PageInfo<Brand> pageInfo = new PageInfo<>(brands);

        long total = pageInfo.getTotal();
        List<BrandDTO> brandDTOS = BeanHelper.copyWithCollection(pageInfo.getList(), BrandDTO.class);
        PageResult<BrandDTO> pageResult = new PageResult<>(total,brandDTOS);
        return pageResult;
    }

    public void saveBrand(BrandDTO brandDTO, List cids) {
        try {
            //保存品牌
            Brand brand = BeanHelper.copyProperties(brandDTO, Brand.class);
            brandMapper.insertSelective(brand);
            //保存中间表
            brandMapper.saveCategoryBrand(brand.getId(),cids);
        } catch (Exception e) {
            throw new LyException(ExceptionEnum.INSERT_OPERATION_FAIL);
        }
    }

    /**
     * 根据品牌id查询品牌dto
     * @param brandId
     * @return
     */
    public BrandDTO findBrandById(Long brandId) {
        Brand brand = brandMapper.selectByPrimaryKey(brandId);
        if (brand==null){
            throw new LyException(ExceptionEnum.BRAND_NOT_FOUND);
        }
        return BeanHelper.copyProperties(brand,BrandDTO.class);
    }

    /**
     * 根据分类id查询品牌集合
     * @param id
     * @return
     */
    public List<BrandDTO> findBrandByCategoryId(Long id) {
        List<Brand> list=brandMapper.findBrandByCategoryId(id);
        return BeanHelper.copyWithCollection(list,BrandDTO.class);
    }
}
